package cn.choujay.tlias.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.CannedAccessControlList;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
@Slf4j
public class COSUtil {

    @Value("${spring.tengxun.SecretId}")
    private String secretId;

    @Value("${spring.tengxun.SecretKey}")
    private String secretKey;

    @Value("${spring.tengxun.region}")
    private String region;

    @Value("${spring.tengxun.bucketName}")
    private String bucketName;

    @Value("${spring.tengxun.url}")
    private String path;

    public String Upload(MultipartFile file) throws IOException {

        log.info("secretId {}", secretId);
        log.info("secretKey {}", secretKey);
        log.info("region {}", region);
        log.info("bucketName {}", bucketName);
        log.info("path {}", path);
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        Region region = new Region(this.region);
        ClientConfig clientConfig = new ClientConfig(region);
        // 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);
        String prefix = UUID.randomUUID().toString();
        String filename = prefix + suffix;
        log.info("filename {}", filename);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filename, inputStream, null);
        cosClient.putObject(putObjectRequest);
        cosClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        COSObject object = cosClient.getObject(bucketName, filename);
        String url = object.getObjectContent().getHttpRequest().getURI().toString();
        return url;
    }

}
